package com.sapp.imagecolorization.retrofit

import android.app.Activity
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import com.sapp.imagecolorization.utils.Utils
import me.relex.photodraweeview.PhotoDraweeView
import okhttp3.MultipartBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class RestApiService {
    private val utils = Utils()

    fun loadUrlImage(
        context: Activity,
        imageData: String,
        imageView: PhotoDraweeView,
        progressBar: ProgressBar
    ) {
        val params: MutableMap<String, String> =
            HashMap()
        params["image"] = imageData

        val retrofit =
            ServiceBuilder.buildService(RestApi::class.java)
        retrofit.postImageUrl(params).enqueue(
            object : Callback<ImageInfo> {
                override fun onResponse(call: Call<ImageInfo>, response: Response<ImageInfo>) {
                    val responseObject = response.body()
                    var imageLink = ""

                    if (responseObject != null) {
                        imageLink = responseObject.output_url
                        imageUrlToDownload = imageLink
                        Log.d("Response", imageUrlToDownload)

                    }

                    if (imageLink != null) {
                        progressBar.visibility = View.GONE
                        utils.loadImageFromUrl(context, imageLink, imageView)
                    }
                }

                override fun onFailure(call: Call<ImageInfo>, t: Throwable) {
                    Log.e("Error", t.message.toString())

                }
            }
        )
    }

    fun loadStorageImage(
        context: Activity,
        imageData: MultipartBody.Part,
        imageView: PhotoDraweeView,
        progressBar: ProgressBar
    ) {

        val params: MutableMap<String, MultipartBody.Part> =
            HashMap()
        params["image"] = imageData

        val retrofit =
            ServiceBuilder.buildService(RestApi::class.java)
        retrofit.postStorageImage(imageData).enqueue(
            object : Callback<ImageInfo> {
                override fun onResponse(call: Call<ImageInfo>, response: Response<ImageInfo>) {
                    val responseObject = response.body()
                    val imageLink = responseObject!!.output_url

                    if (imageLink != null) {
                        imageUrlToDownload = imageLink
                        progressBar.visibility = View.GONE
                        Log.d("Response", imageLink)
                        utils.loadImageFromUrl(context, imageLink, imageView)
                    }

                }

                override fun onFailure(call: Call<ImageInfo>, t: Throwable) {
                    Log.e("Error", t.message.toString())

                }

            }
        )
    }
}